package com.zhentao.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.user.mapper.UsersMapper;
import com.zhentao.user.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UsersMapper usersMapper;
    
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = request.get("username");
            String password = request.get("password");
            String email = request.get("email");
            String phone = request.get("phone");
            String realName = request.get("realName");
            
            // 参数校验
            if (username == null || username.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (password == null || password.length() < 6) {
                response.put("success", false);
                response.put("message", "密码长度不能少于6位");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查用户名是否已存在
            QueryWrapper<Users> usernameQuery = new QueryWrapper<>();
            usernameQuery.eq("username", username);
            Users existingUser = usersMapper.selectOne(usernameQuery);
            if (existingUser != null) {
                response.put("success", false);
                response.put("message", "用户名已存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查邮箱是否已存在
            if (email != null && !email.trim().isEmpty()) {
                QueryWrapper<Users> emailQuery = new QueryWrapper<>();
                emailQuery.eq("email", email);
                Users existingEmailUser = usersMapper.selectOne(emailQuery);
                if (existingEmailUser != null) {
                    response.put("success", false);
                    response.put("message", "邮箱已被注册");
                    return ResponseEntity.badRequest().body(response);
                }
            }
            
            // 检查手机号是否已存在
            if (phone != null && !phone.trim().isEmpty()) {
                QueryWrapper<Users> phoneQuery = new QueryWrapper<>();
                phoneQuery.eq("phone", phone);
                Users existingPhoneUser = usersMapper.selectOne(phoneQuery);
                if (existingPhoneUser != null) {
                    response.put("success", false);
                    response.put("message", "手机号已被注册");
                    return ResponseEntity.badRequest().body(response);
                }
            }
            
            // 创建新用户
            Users newUser = new Users();
            newUser.setUsername(username);
            newUser.setPasswordHash(passwordEncoder.encode(password));
            newUser.setEmail(email);
            newUser.setPhone(phone);
            newUser.setRealName(realName);
            newUser.setStatus(1); // 1表示正常状态
            newUser.setCreatedAt(new Date());
            newUser.setUpdatedAt(new Date());
            
            int result = usersMapper.insert(newUser);
            
            if (result > 0) {
                response.put("success", true);
                response.put("message", "注册成功");
                response.put("userId", newUser.getId());
            } else {
                response.put("success", false);
                response.put("message", "注册失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String loginName = request.get("username"); // 可以是用户名、邮箱或手机号
            String password = request.get("password");
            
            // 参数校验
            if (loginName == null || loginName.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "登录名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (password == null || password.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 查找用户（支持用户名、邮箱、手机号登录）
            QueryWrapper<Users> query = new QueryWrapper<>();
            query.and(wrapper -> wrapper
                .eq("username", loginName)
                .or()
                .eq("email", loginName)
                .or()
                .eq("phone", loginName)
            );
            query.eq("status", 1); // 只查询正常状态的用户
            
            Users user = usersMapper.selectOne(query);
            
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在或已被禁用");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证密码
            if (!passwordEncoder.matches(password, user.getPasswordHash())) {
                response.put("success", false);
                response.put("message", "密码错误");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 登录成功，返回用户信息（不包含密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("phone", user.getPhone());
            userInfo.put("realName", user.getRealName());
            userInfo.put("avatarUrl", user.getAvatarUrl());
            userInfo.put("userType", user.getUserType());
            userInfo.put("status", user.getStatus());
            userInfo.put("createdAt", user.getCreatedAt());
            
            response.put("success", true);
            response.put("message", "登录成功");
            response.put("user", userInfo);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> getUserById(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Users user = usersMapper.selectById(userId);
            
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 返回用户信息（不包含密码）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", user.getId());
            userInfo.put("username", user.getUsername());
            userInfo.put("email", user.getEmail());
            userInfo.put("phone", user.getPhone());
            userInfo.put("realName", user.getRealName());
            userInfo.put("avatarUrl", user.getAvatarUrl());
            userInfo.put("userType", user.getUserType());
            userInfo.put("status", user.getStatus());
            userInfo.put("createdAt", user.getCreatedAt());
            
            response.put("success", true);
            response.put("user", userInfo);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username")
    public ResponseEntity<Map<String, Object>> checkUsername(@RequestParam String username) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            QueryWrapper<Users> query = new QueryWrapper<>();
            query.eq("username", username);
            Users user = usersMapper.selectOne(query);
            
            response.put("success", true);
            response.put("available", user == null);
            response.put("message", user == null ? "用户名可用" : "用户名已存在");
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/{userId}")
    public ResponseEntity<Map<String, Object>> updateUser(@PathVariable Long userId, @RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 检查用户是否存在
            Users existingUser = usersMapper.selectById(userId);
            if (existingUser == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 获取要更新的字段
            String username = request.get("username");
            String email = request.get("email");
            String phone = request.get("phone");
            String realName = request.get("realName");
            String avatarUrl = request.get("avatarUrl");
            String userTypeStr = request.get("userType");
            
            // 如果要修改用户名，检查新用户名是否已被其他用户使用
            if (username != null && !username.trim().isEmpty() && !username.equals(existingUser.getUsername())) {
                QueryWrapper<Users> usernameQuery = new QueryWrapper<>();
                usernameQuery.eq("username", username);
                usernameQuery.ne("id", userId); // 排除当前用户
                Users userWithSameUsername = usersMapper.selectOne(usernameQuery);
                if (userWithSameUsername != null) {
                    response.put("success", false);
                    response.put("message", "用户名已被其他用户使用");
                    return ResponseEntity.badRequest().body(response);
                }
                existingUser.setUsername(username);
            }
            
            // 如果要修改邮箱，检查新邮箱是否已被其他用户使用
            if (email != null && !email.trim().isEmpty() && !email.equals(existingUser.getEmail())) {
                QueryWrapper<Users> emailQuery = new QueryWrapper<>();
                emailQuery.eq("email", email);
                emailQuery.ne("id", userId); // 排除当前用户
                Users userWithSameEmail = usersMapper.selectOne(emailQuery);
                if (userWithSameEmail != null) {
                    response.put("success", false);
                    response.put("message", "邮箱已被其他用户使用");
                    return ResponseEntity.badRequest().body(response);
                }
                existingUser.setEmail(email);
            }
            
            // 如果要修改手机号，检查新手机号是否已被其他用户使用
            if (phone != null && !phone.trim().isEmpty() && !phone.equals(existingUser.getPhone())) {
                QueryWrapper<Users> phoneQuery = new QueryWrapper<>();
                phoneQuery.eq("phone", phone);
                phoneQuery.ne("id", userId); // 排除当前用户
                Users userWithSamePhone = usersMapper.selectOne(phoneQuery);
                if (userWithSamePhone != null) {
                    response.put("success", false);
                    response.put("message", "手机号已被其他用户使用");
                    return ResponseEntity.badRequest().body(response);
                }
                existingUser.setPhone(phone);
            }
            
            // 更新其他字段
            if (realName != null) {
                existingUser.setRealName(realName.trim().isEmpty() ? null : realName);
            }
            
            if (avatarUrl != null) {
                existingUser.setAvatarUrl(avatarUrl.trim().isEmpty() ? null : avatarUrl);
            }
            
            if (userTypeStr != null && !userTypeStr.trim().isEmpty()) {
                try {
                    Object userType = Integer.parseInt(userTypeStr);
                    existingUser.setUserType(userType);
                } catch (NumberFormatException e) {
                    response.put("success", false);
                    response.put("message", "用户类型格式错误");
                    return ResponseEntity.badRequest().body(response);
                }
            }
            
            // 更新修改时间
            existingUser.setUpdatedAt(new Date());
            
            // 执行更新
            int result = usersMapper.updateById(existingUser);
            
            if (result > 0) {
                // 返回更新后的用户信息（不包含密码）
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", existingUser.getId());
                userInfo.put("username", existingUser.getUsername());
                userInfo.put("email", existingUser.getEmail());
                userInfo.put("phone", existingUser.getPhone());
                userInfo.put("realName", existingUser.getRealName());
                userInfo.put("avatarUrl", existingUser.getAvatarUrl());
                userInfo.put("userType", existingUser.getUserType());
                userInfo.put("status", existingUser.getStatus());
                userInfo.put("createdAt", existingUser.getCreatedAt());
                userInfo.put("updatedAt", existingUser.getUpdatedAt());
                
                response.put("success", true);
                response.put("message", "用户信息更新成功");
                response.put("user", userInfo);
            } else {
                response.put("success", false);
                response.put("message", "用户信息更新失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 修改用户密码
     */
    @PutMapping("/{userId}/password")
    public ResponseEntity<Map<String, Object>> updatePassword(@PathVariable Long userId, @RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");
            
            // 参数校验
            if (oldPassword == null || oldPassword.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "原密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            if (newPassword == null || newPassword.length() < 6) {
                response.put("success", false);
                response.put("message", "新密码长度不能少于6位");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查用户是否存在
            Users user = usersMapper.selectById(userId);
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证原密码
            if (!passwordEncoder.matches(oldPassword, user.getPasswordHash())) {
                response.put("success", false);
                response.put("message", "原密码错误");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 更新密码
            user.setPasswordHash(passwordEncoder.encode(newPassword));
            user.setUpdatedAt(new Date());
            
            int result = usersMapper.updateById(user);
            
            if (result > 0) {
                response.put("success", true);
                response.put("message", "密码修改成功");
            } else {
                response.put("success", false);
                response.put("message", "密码修改失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }

    /**
     * 修改用户状态（启用/禁用）
     */
    @PutMapping("/{userId}/status")
    public ResponseEntity<Map<String, Object>> updateUserStatus(@PathVariable Long userId, @RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String statusStr = request.get("status");
            
            // 参数校验
            if (statusStr == null || statusStr.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "状态参数不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            
            Integer status;
            try {
                status = Integer.parseInt(statusStr);
                if (status != 0 && status != 1) {
                    response.put("success", false);
                    response.put("message", "状态值只能是0（禁用）或1（启用）");
                    return ResponseEntity.badRequest().body(response);
                }
            } catch (NumberFormatException e) {
                response.put("success", false);
                response.put("message", "状态格式错误");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 检查用户是否存在
            Users user = usersMapper.selectById(userId);
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 更新状态
            user.setStatus(status);
            user.setUpdatedAt(new Date());
            
            int result = usersMapper.updateById(user);
            
            if (result > 0) {
                response.put("success", true);
                response.put("message", status == 1 ? "用户已启用" : "用户已禁用");
                response.put("status", status);
            } else {
                response.put("success", false);
                response.put("message", "状态修改失败");
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "系统错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
        
        return ResponseEntity.ok(response);
    }
}
